package com.outsourcing.bottle.ui;

import java.util.HashMap;

import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.telephony.TelephonyManager;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.outsourcing.bottle.BasicActivity;
import com.outsourcing.bottle.R;
import com.outsourcing.bottle.db.PlatformAccountTable;
import com.outsourcing.bottle.domain.LocationEntry;
import com.outsourcing.bottle.domain.PlatformAccount;
import com.outsourcing.bottle.domain.PlatformBindConfig;
import com.outsourcing.bottle.domain.UrlConfig;
import com.outsourcing.bottle.util.AppContext;
import com.outsourcing.bottle.util.BasicUIEvent;
import com.outsourcing.bottle.util.HttpUtils;
import com.outsourcing.bottle.util.LocationUtil;
import com.outsourcing.bottle.util.UICore;
/**
 * 
 * @author 06peng
 *
 */
public class BindLoginActivity extends BasicActivity implements BasicUIEvent, OnClickListener {

	private final int login = 1;
	private final int bind_success = 2; 
	private final int bind_error = 3;
	
	private String platform;
	private String openuid;
	private PlatformAccount platformAccount;
	
	private ImageView platformView;
	private TextView nickNameTextView;
	private TextView platformTextView;
	private Button bindView;
	private Button hasAccountView;
	private EditText accountView;
	private EditText passwordView;
	private ImageView close;
	
	private String username;
	private String password;
	private String deviceId;
	
	@Override
	protected void onCreate(Bundle paramBundle) {
		super.onCreate(paramBundle);
		setContentView(R.layout.bind_login);
		try {
			platform = getIntent().getStringExtra("platform");
			openuid = getIntent().getStringExtra("openuid");
			PlatformAccountTable pat = new PlatformAccountTable();
			platformAccount = pat.getPlatformAccount(PlatformBindConfig.getOpenType(platform), openuid);
			initWidget();
			TelephonyManager tm = (TelephonyManager) this.getSystemService(TELEPHONY_SERVICE);
			deviceId = tm.getDeviceId();
			networkLocat();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private void initWidget() {
		platformView = (ImageView) findViewById(R.id.bind_login_platform);
		nickNameTextView = (TextView) findViewById(R.id.bind_login_nickname);
		nickNameTextView.setText(getString(R.string.login_txt_hello) + "," + platformAccount.getNickName());
		platformTextView = (TextView) findViewById(R.id.bind_login_platform_text);
		if (platform.equals(PlatformBindConfig.Sina)) {
			platformView.setBackgroundResource(R.drawable.ico_weibo);
			platformTextView.setText(getString(R.string.login_txt_bind_connect) + getString(R.string.login_txt_weibo));
		} else if (platform.equals(PlatformBindConfig.Douban)) {
			platformView.setBackgroundResource(R.drawable.ico_douban);
			platformTextView.setText(getString(R.string.login_txt_bind_connect) + getString(R.string.login_txt_douban));
		} else if (platform.equals(PlatformBindConfig.Tencent)) {
			platformView.setBackgroundResource(R.drawable.ico_tqq);
			platformTextView.setText(getString(R.string.login_txt_bind_connect) + getString(R.string.login_txt_tencent));
		} else if (platform.equals(PlatformBindConfig.QQ)) {
			platformView.setBackgroundResource(R.drawable.ico_qq);
			platformTextView.setText(getString(R.string.login_txt_bind_connect) + getString(R.string.login_txt_qq));
		} else if (platform.equals(PlatformBindConfig.Renren)) {
			platformView.setBackgroundResource(R.drawable.ico_renren);
			platformTextView.setText(getString(R.string.login_txt_bind_connect) + getString(R.string.login_txt_renren));
		} else if (platform.equals(PlatformBindConfig.Twitter)) {
			platformView.setBackgroundResource(R.drawable.ico_twitter);
			platformTextView.setText(getString(R.string.login_txt_bind_connect) + getString(R.string.login_txt_twitter));
		} else {
			platformView.setBackgroundResource(R.drawable.ico_facebook);
			platformTextView.setText(getString(R.string.login_txt_bind_connect) + getString(R.string.login_txt_facebook));
		}
		
		bindView = (Button) findViewById(R.id.bind_login_bind);
		bindView.setOnClickListener(this);
		
		hasAccountView = (Button) findViewById(R.id.bind_login_bindaccount);
		hasAccountView.setOnClickListener(this);
		
		accountView = (EditText) findViewById(R.id.bind_login_account);
		passwordView = (EditText) findViewById(R.id.bind_login_password);
		passwordView.setOnEditorActionListener(new TextView.OnEditorActionListener() {
			
			@Override
			public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
				if (actionId == EditorInfo.IME_ACTION_UNSPECIFIED) {
					checkLogin();
				}
				return false;
			}
		});
		close = (ImageView) findViewById(R.id.close);
		close.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		if (v == bindView) {
			checkLogin();
		} else if (v == hasAccountView) {
			Intent intent = new Intent(this, BindRegisterActivity.class);
			intent.putExtra("platform", platform);
			intent.putExtra("openuid", openuid);
			startActivity(intent);
			finish();
		} else if (v == close) {
			finish();
		}
	}
	
	private void checkLogin() {
		username = accountView.getText().toString().trim();
		password = passwordView.getText().toString().trim();
		if (username.equals("")) {
			onToast(getString(R.string.login_txt_register_error_account));
			return;
		}
		if (password.equals("")) {
			onToast(getString(R.string.login_txt_reset_error));
			return;
		}
		UICore.eventTask(this, this, login, getString(R.string.init_data), null);
	}
	
	@Override
	public void execute(int mes, Object obj) {
		switch (mes) {
		case login:
			login();
			break;

		default:
			break;
		}
	}
	
	private void login() {
		LocationUtil locationUtil = new LocationUtil(this);
		LocationEntry entry = locationUtil.locate();
		String url = UrlConfig.bind_login;
		HashMap<String, String> paramMaps = new HashMap<String, String>();
		paramMaps.put("username", username);
		paramMaps.put("password", password);
		paramMaps.put("open_type", String.valueOf(platformAccount.getOpenType()));
		paramMaps.put("access_token", platformAccount.getAccessToken());
		paramMaps.put("token_secret", platformAccount.getTokenSecret());
		paramMaps.put("nickname", platformAccount.getNickName());
		paramMaps.put("open_uid", platformAccount.getOpenUid());
		paramMaps.put("open_sex", String.valueOf(platformAccount.getOpenSex()));
		paramMaps.put("open_expire", platformAccount.getOpenExpire());
		paramMaps.put("open_avatar", platformAccount.getOpenAvatar());
		paramMaps.put("device_token", deviceId);
		paramMaps.put("device_type", android.os.Build.MODEL);
		paramMaps.put("device_provider", android.os.Build.HARDWARE);
		paramMaps.put("device_version", android.os.Build.VERSION.RELEASE);
		paramMaps.put("lat", String.valueOf(entry.getLatitude()));
		paramMaps.put("lng", String.valueOf(entry.getLongitude()));
		if (countryIso != null && countryIso.equalsIgnoreCase("cn")) {
			paramMaps.put("location_mode", "1");
		} else {
			paramMaps.put("location_mode", "0");
		}
		try {
			String result = HttpUtils.doPost(this, url, paramMaps);
			if (result != null) {
				JSONObject obj = new JSONObject(result);
				JSONObject resultObj = obj.getJSONObject("results");
				int login_uid = resultObj.getInt("login_uid");
				if (login_uid != 0) {
					String login_token = resultObj.getString("login_token");
					AppContext.getInstance().setLogin_uid(login_uid);
					AppContext.getInstance().setLogin_token(login_token);
					SharedPreferences preferences = getSharedPreferences("Preferences_userinfo", Activity.MODE_APPEND);
					Editor editor = preferences.edit();
					editor.putInt("login_uid", login_uid);
					editor.putString("login_token", login_token);
					editor.commit();
					handler.sendEmptyMessage(bind_success);
				} else {
					String errmsg = resultObj.getString("errmsg");
					Message message = Message.obtain(handler, bind_error, errmsg);
					handler.sendMessage(message);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			case bind_success:
				Intent intent = new Intent(BindLoginActivity.this, HomeActivity.class);
				startActivity(intent);
				BindLoginActivity.this.finish();
				break;
			case bind_error:
				onToast((String) msg.obj);
				break;
			default:
				break;
			}
		}
	};
}
